package com.example.service;

import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class UserService {

    // 导入数据库接口，Dao层
    @Resource
    private UserDao userDao;

    /**
     * 新增和修改
     * @desc 新增与更新，新增不传id，更新传id
     * @param {object} User
     * */
    public void save(User user) {
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        user.setCreateTime(now);
        userDao.save(user);
    }

    /**
     * 删除
     * @param {number} id
     * */
    public void delete(Long id) {
        userDao.deleteById(id);
    }


    /**
     * 根据id查询用户
     * @param {number} id
     * @return {object} User
     * */
    public User findById(Long id) {
        return userDao.findById(id).orElse(null);
    }


    /**
     * 分页查询用户
     * @param {number} pageNum
     * @param {number} pageSize
     * @return
     * */
    public Page<User> findPage(Integer pageNum, Integer pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "create_time");
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
        return userDao.findAll(pageable);
    }

    /**
     * 分页查询用户，模糊查询
     * @param {number} pageNum
     * @param {number} pageSize
     * @param {String} name
     * */
    public Page<User> findFilterPage(Integer pageNum, Integer pageSize, String name) {
        Sort sort = Sort.by(Sort.Direction.DESC, "create_time");
        PageRequest request = PageRequest.of(pageNum - 1, pageSize, sort);
        return userDao.findNameLike(name, request);
    }
}
